﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.Diagnostics;

public class MyCameraFadeScript : MonoBehaviour 
{

    private Mesh PlaneMesh;

    private int TeleportFadeDuration = 3;

    private float TeleportTimeMarker = -1f;

    private bool FadingIn;

    public Material FadeMaterial;

    private int MaterialFadeID;

    private bool isRending;

    private void Start()
    {
        this.PlaneMesh = new Mesh();
        Vector3[] vertices = new Vector3[]
        {
            new Vector3(-1f, -1f, 0f),
            new Vector3(-1f, 1f, 0f),
            new Vector3(1f, 1f, 0f),
            new Vector3(1f, -1f, 0f)
        };
        int[] triangles = new int[]
        {
            0,
            1,
            2,
            0,
            2,
            3
        };
        PlaneMesh.vertices = vertices;
        PlaneMesh.triangles = triangles;
        PlaneMesh.RecalculateBounds();
        MaterialFadeID = Shader.PropertyToID("_Fade");
    }

    private void OnPostRender()
    {
        if (isRending)
        {
            float num = Mathf.Clamp01((Time.time - this.TeleportTimeMarker) / (float)(this.TeleportFadeDuration / 2));
            if (FadingIn)
            {
                num = 1f - num;
            }
            Matrix4x4 rhs = Matrix4x4.TRS(Vector3.forward * 0.3f, Quaternion.identity, Vector3.one);
            FadeMaterial.SetPass(0);
            FadeMaterial.SetFloat(MaterialFadeID, num);
            Graphics.DrawMeshNow(PlaneMesh, transform.localToWorldMatrix * rhs);
        }
    }

    public void Fade(bool isFade)
    {
        this.isRending = true;
        if (isFade)
        {
            FadingIn = false;
            FadeMaterial.SetFloat(MaterialFadeID, 0f);
            TeleportTimeMarker = Time.time;
        }
        else
        {
            FadeMaterial.SetFloat(MaterialFadeID, 1f);
            FadingIn = true;
            TeleportTimeMarker = Time.time;
        }
    }

    public void Fade()
    {
        StartCoroutine("NextFade");
    }

    private void Update()
    {
    }

    [DebuggerHidden]
    private IEnumerator NextFade()
    {
        yield return new WaitForSeconds(1.3f);
        //ToDO
        print(1111);
    }


}
